package com.qiangesoft.jpa.service.impl;

import com.qiangesoft.jpa.dao.SysUserDao;
import com.qiangesoft.jpa.entity.SysUser;
import com.qiangesoft.jpa.service.SysUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务层实现
 *
 * @author qiangesoft
 * @date 2024-10-11
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;


    @Override
    public void save(SysUser sysUser) {
        sysUserDao.save(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        boolean exists = sysUserDao.existsById(id);
        if (exists) {
            sysUserDao.deleteById(id);
        }
    }

    @Override
    public List<SysUser> finaAll() {
        return sysUserDao.findAll();
    }

    @Override
    public Page<SysUser> page(Integer pageNum, Integer pageSize, String nickName) {
        // 排序
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
        Sort sort = Sort.by(orders);

        // 分页
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);

        if (nickName != null && !"".equals(nickName)) {
            // 查询条件
            Specification<SysUser> specification = (root, criteriaQuery, criteriaBuilder) -> {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.like(root.get("nickName"), "%" + nickName + "%"));
                Predicate[] pre = predicateList.toArray(new Predicate[0]);
                return criteriaQuery.where(pre).getRestriction();
            };
            return sysUserDao.findAll(specification, pageRequest);
//            return sysUserDao.pageByNickName("%" + nickName + "%", pageRequest);
        } else {
            return sysUserDao.findAll(pageRequest);
        }
    }

    @Override
    public SysUser findById(Long id) {
        sysUserDao.updateById("王五", 2L);
//        SysUser admin = sysUserDao.findByUserName("admin");
        return sysUserDao.findById(id).orElse(null);
    }
}
